package com.bbm.communitysystem.tools;


import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.bbm.communitysystem.core.domain.Decryption;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;


/**
 * @author xieling
 * @version 1.0
 *
 * 该类用于密码加密解密
 */
@Slf4j
public class SHA256 {


    // 加密器
    private static final Digester digest = new Digester(DigestAlgorithm.SHA256);


    /**
     * SHA256 加密方法
     * @param original 原文
     * */
    public static String encryption(String original) {

        String salt = RandomStringUtils.randomNumeric(16);

        String ciphertext = digest.digestHex(original + salt);

        StringBuilder FinalCiphertext = new StringBuilder(80);

        for (int i = 0; i < 16; i++) {
            FinalCiphertext.append(ciphertext.charAt(i * 4));
            FinalCiphertext.append(salt.charAt(i));
            FinalCiphertext.append(ciphertext.charAt(i * 4 + 1));
            FinalCiphertext.append(ciphertext.charAt(i * 4 + 2));
            FinalCiphertext.append(ciphertext.charAt(i * 4 + 3));
        }

       return FinalCiphertext.toString();
    }


    /**
     * 解密方法
     * @param encrypted 密文
     * */

    public static Decryption decryption(String encrypted) {

        StringBuilder salt = new StringBuilder(16);


        StringBuilder ciphertext = new StringBuilder(64);

        for (int i = 0; i < 16; i++) {

            ciphertext.append(encrypted.charAt(i * 5));
            ciphertext.append(encrypted.charAt(i * 5 + 2));
            ciphertext.append(encrypted.charAt(i * 5 + 3));
            ciphertext.append(encrypted.charAt(i * 5 + 4));
            salt.append(encrypted.charAt(i * 5 + 1));
        }


        Decryption decryption = new Decryption();
        decryption.setEncrypted(ciphertext.toString());
        decryption.setSalt(salt.toString());

        return decryption;
    }


    /**
     * 核实方法
     * @param original 原文
     * @param decryption 后的封装的密文和盐值
     * */

    public static boolean verify(String original,Decryption decryption) {


        String ciphertext = digest.digestHex(original + decryption.getSalt());

        return ciphertext.equals(decryption.getEncrypted());
    }
}
